﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using Infragistics.Win.UltraWinGrid;
using System.Text.RegularExpressions;
namespace DMSClient.General
{
    public partial class EmailList : Form
    {
        private DataTable dtEmailList;
        private DataTable dtPhase;
        private DataTable dtPH;
        string ambiente;
        DataSet dsEmail;
        EndpointAddress address;
        WSHttpBinding Binding = new WSHttpBinding();
        UltraDropDown dd;
        UltraDropDown uddStatus;

        //TOOL TIP

        // DESIGNER GENERATED CODE, ETC.... (elided for clarity)

        // the tooltip that we will use when the cursor is over a cell of the grid
        private System.Windows.Forms.ToolTip tooltip = null;

        // this allows our tooltips to have a delay before appearing
        private Timer timer = new Timer();

        // the message that will be put in the tooltip
        private string msg = String.Empty;

        /// <summary>
        /// ////////////////////////////////////////////////////
        /// </summary>
        
        public EmailList()
        {
            InitializeComponent();
            ambiente = Properties.Settings.Default.CurrentEnv;
            Binding.MaxReceivedMessageSize = 2147483647;
            Binding.MaxBufferPoolSize = 2147483647;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            address = new EndpointAddress(Properties.Settings.Default.Server);

            this.Text = Properties.Settings.Default.CurrentEnvDes + " - Email List";

            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            string distributors = null;
            try
            {
                client.Open();
                distributors = client.getDistribuitorsListWhitCountries();
                client.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (distributors == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }
            DataTable dt = new DataTable("dtDistList");
            dt.Columns.Add("IdCountry");
            dt.Columns.Add("dsCountry");
            dt.Columns.Add("IdDistributor");
            dt.Columns.Add("cdDistributor");
            dt.Columns.Add("dsName");
            dt.Columns.Add("dsCorporateName");
            dt.Columns.Add("idStatus");
            dt.Columns.Add("SendAlerts");
           

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(distributors);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            ugDistribuitors.DataSource = ds.Tables[0];
            ugDistribuitors.DisplayLayout.Bands[0].Columns["IdCountry"].Hidden = true;
            ugDistribuitors.DisplayLayout.Bands[0].Columns["IdDistributor"].Hidden = true;
            ugDistribuitors.DisplayLayout.Bands[0].Columns["SendAlerts"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;

            ugDistribuitors.DisplayLayout.Bands[0].Columns["IdCountry"].CellActivation = Activation.NoEdit;
            ugDistribuitors.DisplayLayout.Bands[0].Columns["dsCountry"].CellActivation = Activation.NoEdit;
             
            ugDistribuitors.DisplayLayout.Bands[0].Columns["cdDistributor"].CellActivation = Activation.NoEdit;
            ugDistribuitors.DisplayLayout.Bands[0].Columns["dsName"].CellActivation = Activation.NoEdit;
            ugDistribuitors.DisplayLayout.Bands[0].Columns["dsCorporateName"].CellActivation = Activation.NoEdit;
            ugDistribuitors.DisplayLayout.Bands[0].Columns["idStatus"].CellActivation = Activation.NoEdit;
            


            xmlSR.Close();

            ugEmailList.DisplayLayout.Bands[0].Columns.Add("idDistributorEmail");
            ugEmailList.DisplayLayout.Bands[0].Columns.Add("idDistributor");
            ugEmailList.DisplayLayout.Bands[0].Columns.Add("dsDistributorEmail");
            ugEmailList.DisplayLayout.Bands[0].Columns.Add("Active");
            ugEmailList.DisplayLayout.Bands[0].Columns["dsDistributorEmail"].Width = 200;
            ugEmailList.DisplayLayout.Bands[0].Columns["Active"].DataType = typeof(bool);
            ugEmailList.DisplayLayout.Bands[0].Columns["Active"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;           
            ugEmailList.DisplayLayout.Bands[0].Columns["idDistributor"].Hidden = true;
            ugEmailList.DisplayLayout.Bands[0].Columns["idDistributorEmail"].Hidden = true;

            // TOOL TIP
           // ugFTP.DataSource = System.Data.Testing.DataMaker.TwoBands;

            // prevent the grid from showing its own tooltips
            ugFTP.DisplayLayout.Override.TipStyleCell = TipStyle.Hide;

            // set this value to however many milliseconds the tooltip delay should be
            timer.Interval = 500;

            // when the timer ticks we want our method to be called
           // timer.Tick += new EventHandler(OnTimerTick);

            

         }
         
        private void OnTimerTick(object sender, EventArgs e)
        {
            tooltip = new System.Windows.Forms.ToolTip();
            tooltip.SetToolTip(ugFTP, msg);
            // once the timer has ticked, stop it
            timer.Stop();
        }

        private void EmailList_Load(object sender, EventArgs e)
        {
            //estadoButton(false);
        }

       

        private void ugDistribuitors_AfterRowActivate(object sender, EventArgs e)
        {
            if (!WorkerEmail.IsBusy)
            {
                WorkerEmail.RunWorkerAsync();
                estado(false);
            }
        }


        //HILO DE CONSULTA DE EMAILS
        private void WorkerEmail_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            int idDistribuitor = -1;
            
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugDistribuitors.Rows)
            {
                if (row.IsActiveRow)
                {
                    idDistribuitor = int.Parse(row.Cells["idDistributor"].Value.ToString());
                    break;
                }
            }
            
            //int idDistributor =  ugEmailList.DisplayLayout.Bands[0].Columns["idDistributor"].
            
                
                
             DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            string lista = null;
            string phase = null;
            string ph = null;
            try
            {

                client.Open();
                if (idDistribuitor != -1)
                {

                    ph = client.getPhases();
                    phase = client.getPhaseBydistributors(idDistribuitor);
                    lista = client.getEmailsBydistributors(idDistribuitor);
                    
                }
                client.Close();
            
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
            if (lista == null)
            {
                throw new Exception("Error");
            }

            dtEmailList = new DataTable("dtEmailList");
            dtEmailList.Columns.Add("idDistributorEmail");
            dtEmailList.Columns.Add("idDistributor");
            dtEmailList.Columns.Add("dsDistributorEmail");
            dtEmailList.Columns.Add("Active");           

            dsEmail = new DataSet();
            dsEmail.Tables.Add(dtEmailList);

            System.IO.StringReader xmlSR = new System.IO.StringReader(lista);
            dsEmail.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            dtPhase = new DataTable("dtPhaseBydistributors");
            dtPhase.Columns.Add("IdDistributorPhase");
            dtPhase.Columns.Add("IdDistributor");
            dtPhase.Columns.Add("IdPhase");           
            dtPhase.Columns.Add("dsStartDate");
            dtPhase.Columns.Add("dsEndDate");
            dtPhase.Columns.Add("nmFTP");
            dtPhase.Columns.Add("nmUserFTP");
            dtPhase.Columns.Add("nmPassFTP");
            dtPhase.Columns.Add("nmFTPFolder");
            dtPhase.Columns.Add("idStatus");

            dsEmail.Tables.Add(dtPhase);
            System.IO.StringReader xmlSR1 = new System.IO.StringReader(phase);
            dsEmail.ReadXml(xmlSR1, XmlReadMode.ReadSchema);

            dtPH = new DataTable("dtPhases");
            dtPH.Columns.Add("idPhase");
            dtPH.Columns.Add("cdPhase");
            dtPH.Columns.Add("dsName");
            dsEmail.Tables.Add(dtPH);
            System.IO.StringReader xmlSR2 = new System.IO.StringReader(ph);
            dsEmail.ReadXml(xmlSR2, XmlReadMode.ReadSchema);

        }
        private void validateUltragrid() 
        {
            if (dsEmail.Tables[0].Rows.Count == 0)
            {
                ugEmailList.Text = "There are not asociated data";
            }
            else
            {
                ugEmailList.Text = "";
            }
            if (dsEmail.Tables[1].Rows.Count == 0)
            {
               ugFTP.Text = "There are not asociated data";
            }
            else
            {
                ugFTP.Text = "";
            }
        
        }
        private void WorkerEmail_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
             
            
            ugEmailList.DataSource = dsEmail.Tables[0];  
            ugFTP.DataSource = dsEmail.Tables[1];
            validateUltragrid();
           


            //ugFTP.DisplayLayout.Bands[0].Columns["Active"].DataType = typeof(bool);
            ugFTP.DisplayLayout.Bands[0].Columns["IdPhase"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownValidate;
            ugFTP.DisplayLayout.Bands[0].Columns["IdDistributor"].Hidden = true;
            ugFTP.DisplayLayout.Bands[0].Columns["IdDistributorPhase"].Hidden = true;
            ugFTP.DisplayLayout.Bands[0].Columns["idStatus"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownValidate;
            ugFTP.DisplayLayout.Bands[0].Columns["dsStartDate"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DateTime;
            ugFTP.DisplayLayout.Bands[0].Columns["dsEndDate"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DateTime;
            ugFTP.DisplayLayout.Bands[0].Columns["dsStartDate"].Width = 150;
            ugFTP.DisplayLayout.Bands[0].Columns["dsEndDate"].Width = 150;
            ugFTP.DisplayLayout.Bands[0].Columns["nmFTP"].Width = 320;
            ugFTP.DisplayLayout.Bands[0].Columns["nmUserFTP"].Width = 250;
            ugFTP.DisplayLayout.Bands[0].Columns["nmPassFTP"].Width = 150;
            ugFTP.DisplayLayout.Bands[0].Columns["nmFTPFolder"].Width = 200;
            
            BindUltraDropDown();
            estado(true);
            if (dsEmail.Tables[0].Rows.Count != 0) 
            {
                DeleteEmail.Visible = true;
            }
            else
            {
                DeleteEmail.Visible = false;
            }
            if (dsEmail.Tables[1].Rows.Count != 0)
            {
                DeleteFTP.Visible = true;
            }
            else 
            {
                DeleteFTP.Visible = false;
            }
        }

        public void estado(bool estado)
        {
            ugDistribuitors.Enabled = estado;
            ugFTP.Enabled = estado;
            loader.BringToFront();
            loader.Visible = !estado;
            ubSave.Enabled = estado;
            ubCancel.Enabled = estado; ;
            

        }

        private void estadoButton(bool estado) 
        {
            ubCancel.Enabled = estado;
            ubSave.Enabled = estado;
            
        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {
            int count = 0;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugEmailList.Rows)
            {
               
                if (row.Cells["idDistributorEmail"].Value.ToString().Equals("") &&
                    row.Cells["idDistributor"].Value.ToString().Equals("") &&
                    row.Cells["dsDistributorEmail"].Value.ToString().Equals(""))
                {
                    count++;

                }


            }
            if (count > 0)
            {
                MessageBox.Show("There are empty rows, delete or complete these rows","Email List");
            }
            else
            {
                ugEmailList.Rows.Band.AddNew();
                ugEmailList.Text = "";
                foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugEmailList.Rows)
                {
                    if (row.IsActiveRow) 
                    {
                        row.Cells["Active"].Value = false;
                    }
                }
            }
            
            
        }

        private void ugDistribuitors_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
             
        }

        private void ugEmailList_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void BindUltraDropDown()
        {
            try
            {
                DataTable dt1 = new DataTable();
                dt1.Columns.Add("Status", typeof(string));
                // dt.Columns.Add("DisplayText", typeof(string));

                dt1.Rows.Add("ACT");
                dt1.Rows.Add("DEACT");
                dt1.AcceptChanges();
                uddStatus = new UltraDropDown();
                uddStatus.SetDataBinding(dt1, null);
                uddStatus.ValueMember = "Status";
                uddStatus.DisplayMember = "Status";
                //uddStatus.               
                dd = new UltraDropDown();
                dd.SetDataBinding(dtPH, null);
                dd.ValueMember = "idPhase";
                dd.DisplayMember = "cdPhase";
            }
            catch (Exception ex) { }
        }

        private void ugFTP_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
            e.Layout.Bands[0].Columns["IdPhase"].ValueList = this.dd;
            e.Layout.Bands[0].Columns["idStatus"].ValueList = this.uddStatus;
        }

        private void ultraButton3_Click(object sender, EventArgs e)
        {
            int count = 0;
            bool FilaActiva = false;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugDistribuitors.Rows)
            {
                if (row.IsActiveRow) 
                {
                    FilaActiva = true; 
                }
            }
            if (FilaActiva)
            {
                foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugFTP.Rows)
                {


                    if (row.Cells["IdDistributorPhase"].Value.ToString().Equals("") &&
                        row.Cells["IdDistributor"].Value.ToString().Equals("") &&
                        row.Cells["IdPhase"].Value.ToString().Equals("") &&
                        row.Cells["dsStartDate"].Value.ToString().Equals("") &&
                        row.Cells["dsEndDate"].Value.ToString().Equals("") &&
                        row.Cells["nmFTP"].Value.ToString().Equals("") &&
                        row.Cells["nmUserFTP"].Value.ToString().Equals("") &&
                        row.Cells["nmPassFTP"].Value.ToString().Equals("") &&
                        row.Cells["nmFTPFolder"].Value.ToString().Equals("") &&
                        row.Cells["idStatus"].Value.ToString().Equals(""))
                    {
                        count++;

                    }


                }
                if (count > 0)
                {
                    MessageBox.Show("There are empty rows, delete or complete these rows", "FTP List");
                }
                else
                {
                    ugFTP.Rows.Band.AddNew();
                    ugFTP.Text = "";
                }
            }
            else 
            {
                MessageBox.Show("Please , choose a Distributor!");
            }
        }


        #region SAVE

        private void ultraButton2_Click(object sender, EventArgs e)
        {
            bool sw = false;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugFTP.Rows)
            {
                if (row != null)
                {
                    if (validatePhase(row))
                    {
                        sw = true;
                    }
                    else 
                    {
                        sw = false;
                    }
                }
                
            }
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugEmailList.Rows)
            {
                if (row != null)
                {
                    if (validateEmail(row))
                    {
                        sw = true;
                    }
                    else
                    {
                        sw = false;
                    }

                    if (validateFormatEmail(row.Cells["dsDistributorEmail"].Value.ToString()))
                    {
                        sw = true;
                    }
                    else
                    {
                        sw = false;
                        MessageBox.Show("The format to email is incorrect!", "Email List");
                        return;
                    }


                }

            }
            if (sw && !validateDuplicatedEmail())
            {
                estado(false);                
                WorkerSave.RunWorkerAsync();
            }
            

        }

        private void WorkerSave_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            int idDistribuitor = -1;
            bool sendAlert = false;

            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugDistribuitors.Rows)
            {
                if (row.IsActiveRow)
                {
                    idDistribuitor = int.Parse(row.Cells["idDistributor"].Value.ToString());
                    sendAlert = bool.Parse(row.Cells["SendAlerts"].Value.ToString());
                    break;
                }
            }
            if (idDistribuitor != -1)
            {


                List<Dtl.DistribuitorEmail> listEmail = new List<Dtl.DistribuitorEmail>();
                List<Dtl.DistribuitorPhase> lisDistPhase = new List<Dtl.DistribuitorPhase>();

                //GUARDO EN LA LISTA DE PHASE
                foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugFTP.Rows)
                {
                    if (row != null)
                    {
                            Dtl.DistribuitorPhase DistribuitorPhase = new Dtl.DistribuitorPhase();
                            DistribuitorPhase.IdDistributor = idDistribuitor;
                            DistribuitorPhase.IdPhase = int.Parse(row.Cells["IdPhase"].Value.ToString());
                            DistribuitorPhase.dsStartDate = DateTime.Parse(row.Cells["dsStartDate"].Value.ToString());
                            DistribuitorPhase.dsEndDate = DateTime.Parse(row.Cells["dsEndDate"].Value.ToString());
                            DistribuitorPhase.nmFTP = row.Cells["nmFTP"].Value.ToString();
                            DistribuitorPhase.nmUserFTP = row.Cells["nmUserFTP"].Value.ToString();
                            DistribuitorPhase.nmPassFTP = row.Cells["nmPassFTP"].Value.ToString();
                            DistribuitorPhase.nmFTPFolder = row.Cells["nmFTPFolder"].Value.ToString();
                            DistribuitorPhase.idStatus = row.Cells["idStatus"].Value.ToString();

                            if (row.Cells["IdDistributorPhase"].Value.ToString().Equals(""))
                            {
                                DistribuitorPhase.typeOperation = true;
                            }
                            else
                            {
                                DistribuitorPhase.typeOperation = false;
                                DistribuitorPhase.IdDistributorPhase = int.Parse(row.Cells["IdDistributorPhase"].Value.ToString());
                            }

                            lisDistPhase.Add(DistribuitorPhase);

                        
                    }
                    
                }

                //GUARDO EN LA LISTA DE EMAIL
                foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugEmailList.Rows)
                {
                    if (row != null)
                    {
                        Dtl.DistribuitorEmail DistribuitorEmail = new Dtl.DistribuitorEmail();
                        DistribuitorEmail.idDistributor = idDistribuitor;
                        DistribuitorEmail.dsDistributorEmail = row.Cells["dsDistributorEmail"].Value.ToString();
                        DistribuitorEmail.active = bool.Parse(row.Cells["Active"].Value.ToString());

                        if (row.Cells["idDistributorEmail"].Value.ToString().Equals(""))
                        {
                            DistribuitorEmail.typeOperation = true;
                        }
                        else
                        {
                            DistribuitorEmail.typeOperation = false;
                            DistribuitorEmail.idDistributorEmail = int.Parse(row.Cells["idDistributorEmail"].Value.ToString());
                        }
                        listEmail.Add(DistribuitorEmail);
                    }

                }
                try
                {
                    client.Open();
                    if (client.setDistribuitorPhaseAndEmail(idDistribuitor,sendAlert,listEmail,lisDistPhase) == 1)
                    {
                        MessageBox.Show("Successfully saved record!", "Email List");

                    }
                    else
                    {
                        MessageBox.Show("Error saving the record, please try again!", "Email List");
                    }
                    client.Close();
                    if (WorkerSave.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }          

             }
        }

        private void WorkerSave_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                estado(true);
                WorkerEmail.RunWorkerAsync();
            }
        }

        #endregion

        #region DELETE FTP
        private void ultraButton5_Click(object sender, EventArgs e)
        {
            bool FILA = false;
            string id = "";
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugFTP.Rows)
            {
                if (row.IsActiveRow)
                {
                    FILA = true;
                    
                }
            }
            if (FILA)
            {
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                string caption = "FTP";
                string mensaje = "Do You're  sure that want to delete the record ?";
                DialogResult resultado = MessageBox.Show(mensaje, caption, buttons);


                if (resultado == DialogResult.Yes)
                {
                    estado(false);
                    WorkerDeleteFTP.RunWorkerAsync();
                }
            }
            else 
            {

                MessageBox.Show("Please, choose you a row of FTP/SFTP to deleted!", "FTP");
            }
            
        }
        private void WorkerDeleteFTP_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            int IdDistributorPhase = -1;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugFTP.Rows)
            {
                if (row.IsActiveRow)
                {
                    IdDistributorPhase = int.Parse(row.Cells["IdDistributorPhase"].Value.ToString());
                }
            }

            if (IdDistributorPhase != -1) 
            {
                try
                {
                    client.Open();
                    if (client.DeletePhase(IdDistributorPhase) == 1)
                    {
                        MessageBox.Show("Successfully deleted record!", "FTP");

                    }
                    else
                    {
                        MessageBox.Show("Error deleted the record, please try again!", "FTP");
                    }
                    client.Close();
                    if (WorkerDeleteFTP.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }

            }
            else
            {
                MessageBox.Show("Error deleted the record, please try again!", "FTP");
            }
        }

        private void WorkerDeleteFTP_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                estado(true);
                WorkerEmail.RunWorkerAsync();
            }
        }
        #endregion

        #region DELETE EMAIL
        private void ultraButton4_Click(object sender, EventArgs e)
        {
            bool FILA = false;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugEmailList.Rows)
            {
                if (row.IsActiveRow)
                {
                    FILA = true;
                }
            }
            if (FILA)
            {
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                string caption = "Email";
                string mensaje = "Do You're  sure that want to delete the record ?";
                DialogResult resultado = MessageBox.Show(mensaje, caption, buttons);


                if (resultado == DialogResult.Yes)
                {
                    estado(false);
                    WorkerDeleteEmail.RunWorkerAsync();
                }
            }
            else
            {

                MessageBox.Show("Please, choose you a row of Email List to deleted!", "Email List");
            }
            
           
        }

        private void WorkerDeleteEmail_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            int idDistribuitorMail = -1;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugEmailList.Rows)
            {
                if (row.IsActiveRow)
                {
                    idDistribuitorMail = int.Parse(row.Cells["idDistributorEmail"].Value.ToString());
                }
            }

            if (idDistribuitorMail != -1)
            {
                try
                {
                    client.Open();
                    if (client.DeleteEmail(idDistribuitorMail) == 1)
                    {
                        MessageBox.Show("Successfully deleted record!", "Email List");

                    }
                    else
                    {
                        MessageBox.Show("Error deleted the record, please try again!", "Email List");
                    }
                    client.Close();
                    if (WorkerEmail.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }

            }
            else
            {
                MessageBox.Show("Error deleted the record, please try again!", "Email List");
            }
        }

        private void WorkerDeleteEmail_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                 estado(true);
                 WorkerEmail.RunWorkerAsync();
            }
        }

        #endregion

        private bool validate(string field) 
        {
            if (field.Equals("")) 
            {
                MessageBox.Show("Please set the field IdPhase");
                return false;
            }
            return true;
        
        }
        private bool validatePhase(UltraGridRow row) 
        {

             
            
            if (row.Cells["IdPhase"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field IdPhase");
                return false;
            }

            if (row.Cells["dsStartDate"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field dsStartDate");
                return false;
            }
          /*  if (!IsDate(row.Cells["dsStartDate"].Value.ToString()))
            {
                MessageBox.Show("The field dsStartDate");
                return false;
            }*/
            
            if (row.Cells["dsEndDate"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field dsEndDate");
                return false;
            }
            if (row.Cells["nmFTP"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field nmFTP");
                return false;
            }
            if (row.Cells["nmUserFTP"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field nmUserFTP");
                return false;
            }
            if (row.Cells["nmPassFTP"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field nmPassFTP");
                return false;
            }
          /*  if (row.Cells["nmFTPFolder"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field nmFTPFolder");
                return false;
            }*/
            if (row.Cells["idStatus"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field idStatus");
                return false;
            }

            return true;
        }

        public static bool IsDate(string inValue)
        {
            bool result;
            try
            {
                DateTime myDT = DateTime.Parse(inValue);
                result = true;
            }
            catch (FormatException e)
            {
                result = false;
            }

            return result;
        }

        private bool validateEmail(UltraGridRow row)
        {
            if (row.Cells["dsDistributorEmail"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field dsDistributorEmail!");
                return false;
            }

           

            return true; 
        }

        private bool validateDuplicatedEmail() 
        {
            string email = null;
            bool duplicatedEmail = false;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugEmailList.Rows)
            {

                if (row.Index != 0)
                {
                    if (email.Equals(row.Cells["dsDistributorEmail"].Value.ToString()))
                    {
                        duplicatedEmail = true;
                        MessageBox.Show("There are duplicated Email values!", "Email List");
                        break;
                    }
                }
                email = row.Cells["dsDistributorEmail"].Value.ToString();
                 
            
            }
            return duplicatedEmail;
        }

        private Boolean validateFormatEmail(String email)
        {
            String expresion;
            expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
            if (Regex.IsMatch(email, expresion))
            {
                if (Regex.Replace(email, expresion, String.Empty).Length == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        private void EmailList_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void EmailList_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void ultraButton4_Click_1(object sender, EventArgs e)
        {
            WorkerEmail.RunWorkerAsync();
            estado(false);
        }

         
        // activa la primera fila del ultragrid después de aplicar el filtro
        private void ugDistribuitors_AfterRowFilterChanged(object sender, AfterRowFilterChangedEventArgs e)
        {
            try
            {
                UltraGridRow firstVisibleRow = this.ugDistribuitors.Rows.GetRowAtVisibleIndex(0);
                firstVisibleRow.Cells["dsCountry"].Activate();
            }
            catch (NullReferenceException ex) { }

        }

        private void ugFTP_Move(object sender, EventArgs e)
        {
            //if(e.GetType().
        }

        private void ultraToolTipManager1_PropertyChanged(object sender, Infragistics.Win.PropertyChangedEventArgs e)
        {

        }

        private void ugFTP_MouseMove(object sender, MouseEventArgs e)
        {
           // MessageBox.Show(e.Button.ToString());
        }

        private void ugFTP_MouseEnterElement(object sender, Infragistics.Win.UIElementEventArgs e)
        {
    /*        // if we are not entering a cell, then don't anything
            if (!(e.Element is CellUIElement))
            {
                return;
            }

            // find the cell that the cursor is over, if any
            UltraGridCell cell = e.Element.GetContext(typeof(UltraGridCell)) as UltraGridCell;
            if (cell != null)
            {
                CreateToolTipMessage(cell);
                timer.Stop();
                timer.Start();
            }*/
        }

        private void ugFTP_MouseLeaveElement(object sender, Infragistics.Win.UIElementEventArgs e)
        {

            // if we are not leaving a cell, then don't anything
            if (!(e.Element is CellUIElement))
            {
                return;
            }

            // prevent the timer from ticking again
            timer.Stop();

            // destroy the tooltip
            if (tooltip != null)
            {
                tooltip.SetToolTip(this, String.Empty);
                tooltip.Dispose();
                tooltip = null;
            }


        }

        private void CreateToolTipMessage(UltraGridCell cell)
        {
            if (cell.Band.Index == 0)
            {
                int orderCount = 0;
                UltraGridRow childRow = cell.Row.GetChild(ChildRow.First);
                while (childRow != null)
                {
                    ++orderCount;
                    childRow = childRow.GetSibling(SiblingRow.Next);
                }
                msg = String.Format(cell.Column.ToString());
                ultraToolTipManager1.ToolTipTitle = cell.Column.ToString();
                ultraToolTipManager1.ShowToolTip(ugFTP);
            }
            else
            {
                string fname = cell.Row.ParentRow.Cells["fname"].Text;
                string lname = cell.Row.ParentRow.Cells["lname"].Text;
                msg = String.Format("Order for {0}, {1}", lname, fname);
            }
        }

        private void ugFTP_AfterRowActivate(object sender, EventArgs e)
        {
            validarBotonDeleteFTP();
        }

        private void ugFTP_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            validarBotonDeleteFTP();
        }

        private void validarBotonDeleteFTP() 
        {

            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugFTP.Rows)
            {
                if (row.IsActiveRow)
                {
                    if (row.Cells["IdDistributorPhase"].Value.ToString().Equals(""))
                    {
                        DeleteFTP.Visible = false;
                    }
                    else
                    {
                        DeleteFTP.Visible = true;
                    }
                }
            }
        }

        private void ugEmailList_AfterRowActivate(object sender, EventArgs e)
        {
            validarBotonDeleteEmail();
        }

        private void ugEmailList_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            validarBotonDeleteEmail();
        }

        private void validarBotonDeleteEmail()
        {

            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugEmailList.Rows)
            {
                if (row.IsActiveRow)
                {
                    if (row.Cells["idDistributorEmail"].Value.ToString().Equals(""))
                    {
                        DeleteEmail.Visible = false;
                    }
                    else
                    {
                        DeleteEmail.Visible = true;
                    }
                }
            }
        }

        

        private void ugDistribuitors_FilterCellValueChanged(object sender, FilterCellValueChangedEventArgs e)
        {

        }
         
    }
}
